<?php
declare (strict_types = 1);

namespace app\controller\sys;

use think\facade\View;

use app\model\Carousel as CarouselModel;
use app\utils\ReUtils;

/**
 * 轮播图管理
 */
class Carousel extends Base
{
    protected $modelName = "Carousel";

    public $types = ['图片', '视频'];

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $params = $this->app->request->param();

        $list = CarouselModel::queryPage($params);

        View::assign(['types' => $this->types, 'list' => $list]);
        
        return View::fetch();
    }

    /**
     * 保存新建的资源
     *
     * @param  int  $id 
     * @return \think\Response
     */
    public function save($id = 0)
    {
        if ($this->app->request->isPost()) {
            $params = $this->app->request->param();

            if ($params['title'] == '') {
                $this->error("名称不能为空");
            }

            try {
                $id = $params['id'];
                unset($params['id']);

                if ($id != 0) {
                    CarouselModel::update($params, ['id' => $id]);
                } else {
                    CarouselModel::create($params);
                }

                return ReUtils::success();
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                return ReUtils::error($msg);
            }
        } else {
            if ($id != 0) {
                $data = CarouselModel::find($id);
            } else {
                $data = new CarouselModel();
                $data->status = 1;
                $data->type = 0;
            }
    
            View::assign('data', $data);

            View::assign('types', $this->types);
    
            return View::fetch();
        }
    }
}
